﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using DTO;

namespace DAO
{

	public class ItemDAO:IData<Item> 
 	{
		public ItemDAO(String myconnecString) : base(myconnecString) { }

		protected override int InsertOnSubmit(ref Item item, int t) {
			 SqlParameter p = new SqlParameter(); 
			 if( t == 0)
				p.Direction = ParameterDirection.Output;
			 p.ParameterName = "@" + Item.c_id;
			 p.Value = item.id;
			 Object obj = item.id; 
			int i = connec.ExecuteNonQuery("sp_Item", CommandType.StoredProcedure,p,ref obj,new SqlParameter("@flag", t),
				 new SqlParameter("@" + Item.c_menu_id, item.menu_id), new SqlParameter("@" + Item.c_group_id, item.group_id),
				 new SqlParameter("@" + Item.c_show, item.show), new SqlParameter("@" + Item.c_isadd, item.isadd),
				 new SqlParameter("@" + Item.c_edit, item.edit), new SqlParameter("@" + Item.c_isdelete, item.isdelete),
				 new SqlParameter("@" + Item.c_state, item.state));
			if(t == 0)
				item.id = Convert.ToInt64(obj);
			return i;
		}

		public override Item GetItem(IDataReader dr)
		{
			Item obj = new Item();
			obj.id = Convert.ToInt64(dr[Item.c_id]);
			obj.menu_id = Convert.ToInt64(dr[Item.c_menu_id]);
			obj.group_id = Convert.ToInt64(dr[Item.c_group_id]);
			obj.show = Convert.ToBoolean(dr[Item.c_show]);
			obj.isadd = Convert.ToBoolean(dr[Item.c_isadd]);
			obj.edit = Convert.ToBoolean(dr[Item.c_edit]);
			obj.isdelete = Convert.ToBoolean(dr[Item.c_isdelete]);
			obj.state = Convert.ToBoolean(dr[Item.c_state]);
            obj.name = Convert.ToString(dr[Item.c_name]);
            obj.title = Convert.ToString(dr[Item.c_title]);
            obj.level1 = Convert.ToInt32(dr[Item.c_level1]);
			return obj;
		}

		public override List<Item> GetAll()
		{
			return GetAll("sp_GetAllItem", CommandType.StoredProcedure);
		}

		public override Item GetItemById(object id)
		{
			return GetAll().SingleOrDefault(p => p.id == Convert.ToInt64(id));
		}

		public override Item GetItemById(Item item){
			throw new NotImplementedException();
		}

        private void updateItems(long groupid) {
            connec.ExecuteNonQuery("sp_InsertItemsMenu", new SqlParameter("@group_id", groupid));
        }

        public List<Item> GetModules(long groupid)
        {
            List<Item> list = this.GetListParameter("sp_getMenugroupId", CommandType.StoredProcedure, new SqlParameter("@group_id", groupid));
            if (list.Count == 0) {
                updateItems(groupid);
                list = this.GetListParameter("sp_getMenugroupId", CommandType.StoredProcedure, new SqlParameter("@group_id", groupid));
            }
            return list;
        }
	}

 }
